<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>


    <meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Advanced Storage Example</title>

<style type="text/css">
/*margin and padding on body element
  can introduce errors in determining
  element position and are not recommended;
  we turn them off as a foundation for YUI
  CSS treatments. */
body {
	margin:0;
	padding:0;
}
</style>

<link rel="stylesheet" type="text/css" href="../../build/fonts/fonts-min.css" />
<link rel="stylesheet" type="text/css" href="../../build/button/assets/skins/sam/button.css" />
<link rel="stylesheet" type="text/css" href="../../build/datatable/assets/skins/sam/datatable.css" />
<script type="text/javascript" src="../../build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="../../build/element/element-min.js"></script>
<script type="text/javascript" src="../../build/cookie/cookie-min.js"></script>
<script type="text/javascript" src="../../build/swf/swf-min.js"></script>
<script type="text/javascript" src="../../build/swfstore/swfstore-min.js"></script>
<script type="text/javascript" src="../../build/button/button-min.js"></script>
<script type="text/javascript" src="../../build/datasource/datasource-min.js"></script>
<script type="text/javascript" src="../../build/event-delegate/event-delegate-min.js"></script>
<script type="text/javascript" src="../../build/datatable/datatable-min.js"></script>
<script type="text/javascript" src="../../build/storage/storage-min.js"></script>


<!--begin custom header content for this example-->
<style type="text/css">
label.left
{
	clear: left;
	float: left;
	width: 7em; 
} 

</style>

<!--end custom header content for this example-->

</head>

<body class="yui-skin-sam">


<h1>Advanced Storage Example</h1>

<div class="exampleIntro">
	<p>This example shows how to get, set, and remove items from storage using the <a href="http://developer.yahoo.com/yui/storage/">YUI Storage Utility</a> and how to display the current storage contents in a <a href="http://developer.yahoo.com/yui/datatable/">DataTable</a>.</p>
			
</div>

<!--BEGIN SOURCE CODE FOR EXAMPLE =============================== -->

<!--Input Controls-->

<div id="controls"> 
    <label for="nameField" class="left">Storage name:</label> 
    <input id="nameField" type="text" value=""/>
    <input id="save-button" name="save-button" type="Button" value="Save" /> <input id="remove-button" name="remove-button" type="Button" value="Remove" />
     
    <br/>
 
    <label for="valueField" class="left">Text to store:</label>
    <textarea cols="30" id="valueField" rows="5"></textarea>
    <br/>   <br/>
    
    <fieldset id="checkboxOptions">
        <legend>Additional Options:</legend>
        <div id="engineGroup" class="inline">
            <input id="html5-button" name="html5-button" type="radio" value="Use HTML5" checked="checked" /> 
            <input id="gears-button" name="gears-button" type="radio" value="Use Gears"/> 
            <input id="swf-button" name="swf-button" type="radio" value="Use SWF"/>
            <input id="purge-button" name="purge-button" type="button" value="Purge All Local Data" />
        </div>

        <br/>
        <input id="session-checkbox" type="checkbox"/>
        <label for="session-checkbox">Session storage only</label>
    </fieldset>

    <br/><br/>


    <div id="datatableContainer"></div> 
</div>

<!--Always include gears_init.js when you want to support Google Gears: -->
<script type="text/javascript" src="../storage/assets/gears_init.js"></script>

<!--Local Scripts-->
<script type="text/javascript" >
    /**
     * Pointer to the Storage instance
     */
    var storage;
        
    YAHOO.util.StorageEngineSWF.SWFURL = 'swfstore.swf';

    /**
     * Pointer to the DataTable instance
     */
    var datatable; 

    var saveButton;
    var purgeButton;
    var removeButton;
    var sessionCheckbox = document.getElementById('session-checkbox');
    
    var gearsCheckbox, engineRadio;

    /**
     * Initialization scripts
     */ 
     function initialize() {
        // evaluate and create the Storage instance
        var engineBtn = engineRadio.get("checkedButton");
        var engineType = engineBtn.get("value");
        var useSession = sessionCheckbox.checked;
        var location;

        location = YAHOO.util.StorageManager[useSession ? 'LOCATION_SESSION' : 'LOCATION_LOCAL'];
        storage = YAHOO.util.StorageManager.get(engineType, location, {force: false});

        //storage.unsubscribe(storage.CE_CHANGE, onChange);
        storage.subscribe(storage.CE_CHANGE, onChange);
        
        if (storage.isReady || (storage._swf && YAHOO.util.StorageManager.LOCATION_SESSION === location)) {
            load();
        } else {
            saveButton.set("disabled", true); 
            purgeButton.set("disabled", true);  
            removeButton.set("disabled", true); 
            
            engineRadio.set("disabled", true);
        
            storage.subscribe(storage.CE_READY, onContentReady);
        }
    }
    
    /**
     * This gets called once Storage is initialized and ready to be used. 
     * We disabled the buttons previously, so once they're usable we'll enable them here.
     */ 
    function onContentReady(event) {
        saveButton.set("disabled", false); 
        purgeButton.set("disabled", false);  
        removeButton.set("disabled", false);
        
        engineRadio.set('disabled', false);
        engineRadio._buttons[0].set("disabled", ! YAHOO.util.StorageEngineHTML5.isAvailable()); 
        engineRadio._buttons[1].set("disabled", ! YAHOO.util.StorageEngineGears.isAvailable()); 
        engineRadio._buttons[2].set("disabled", ! YAHOO.util.StorageEngineSWF.isAvailable());
        
        storage.unsubscribe(storage.CE_READY, onContentReady);

        load();
    }

    /**
     * Clear out all data
     */     
    function purge() {
        storage.clear();
        datatable.deleteRows(0, datatable.getRecordSet().getLength());
    }
    
    /**
     * Called when a save is successful
     */     
    function onChange(event) {
        if (event.type === YAHOO.util.StorageEvent.TYPE_ADD_ITEM || event.type === YAHOO.util.StorageEvent.TYPE_UPDATE_ITEM)
        {
            var newobj = {name: event.key, value: event.newValue};

            var len = datatable.getRecordSet().getLength();
        
            //loop through current records and see if this has been added before
            for (var i = 0; i < len; i++ )
            {
                var rec = datatable.getRecord(i);
                var data = rec.getData();
                
                //if it's been added already, update it
                if (data.name == event.key)
                {
                    datatable.updateRow(i, newobj);
                    return;
                }
            }
    
            //if it's not been added, add it
            datatable.addRow(newobj);
        }

        //removed
        else if (event.type === YAHOO.util.StorageEvent.TYPE_REMOVE_ITEM)
        {

            var len = datatable.getRecordSet().getLength();
        
            //loop through current records and see if this has been added before
            for (var i = 0; i < len; i++ )
            {
                var rec = datatable.getRecord(i);
                var data = rec.getData();
                
                //if it's been added already, update it
                if (data.name == event.key)
                {
                    datatable.deleteRow(i);
                    return;
                }
            }
        }       
    }

    
    /**
     * Called when something bad happens
     */         
    function onError(event) {
        alert("Event " + event.message);
    }

    
    /**
     * Gets the data from Storage when the page loads
     */         
    function load() {
 
      var len = storage.length;
      
        var arr = [];

        // clear the existing datatable
        if (datatable)
        {
            datatable.deleteRows(0, datatable.getRecordSet().getLength());
        }
          
        for (var i = 0, key, newobj; i < len; i++)
        {
            key = storage.key(i);
            newobj = { name:key, value: storage.getItem(key) };
            arr.push(newobj);
            if (datatable) {datatable.addRow(newobj);}
        }
        
        // only initialize the datatable once
        if (! datatable)
        {
            var datasource = new YAHOO.util.LocalDataSource(arr); 

            datasource.responseSchema = {fields : ["name", "value"]};
        
            var configs = 
            {   
                scrollable: true
            }
            
            var columns = 
            [
                {key:"name", label:"Storage Name (Key)"},
                {key:"value", label:"Text Stored"}
            ];
                
            datatable = new YAHOO.widget.DataTable("datatableContainer", columns, datasource, configs);
        }
    }
    
    /**
     * Save the data locally
     */ 
    function save() {
        storage.setItem(YAHOO.util.Dom.get('nameField').value, YAHOO.util.Dom.get('valueField').value);
    }

    /**
     * Remove an item from storage
     */ 
    function remove() {
        var key = YAHOO.util.Dom.get('nameField').value;
        storage.removeItem(key);
    }

/**
 * Called when the buttons are ready to be initialized
 */ 
    function onButtonsReady() {
        saveButton = new YAHOO.widget.Button("save-button");
        purgeButton = new YAHOO.widget.Button("purge-button");
        removeButton = new YAHOO.widget.Button("remove-button");
        
        engineRadio = new YAHOO.widget.ButtonGroup("engineGroup");
        
        engineRadio._buttons[0].set("value", YAHOO.util.StorageEngineHTML5.ENGINE_NAME); 
        engineRadio._buttons[1].set("value", YAHOO.util.StorageEngineGears.ENGINE_NAME); 
        engineRadio._buttons[2].set("value", YAHOO.util.StorageEngineSWF.ENGINE_NAME); 

        saveButton.on("click", save); 
        purgeButton.on("click", purge); 
        removeButton.on("click", remove);

        YAHOO.util.Event.addListener(sessionCheckbox, "click", initialize);
        engineRadio.on("checkedButtonChange", initialize);
        
        //initialize
        initialize();
        
        YAHOO.util.Dom.get('nameField').focus()
    }

    YAHOO.util.Event.onContentReady("controls", onButtonsReady);

</script>

<!--END SOURCE CODE FOR EXAMPLE =============================== -->

</body>
</html>
